package chapter11.section4;

/* CLerk 模拟银行职员*/

import java.util.Random;

public class Clerk extends Thread {
    private final QueueMachine queue;// 排队机的引用
    private final String name;

    public Clerk(QueueMachine queue, String name) {
        super(name);
        this.queue = queue;
        this.name = name;
    }

    public Clerk(QueueMachine queue, String name, ThreadGroup group) {
        super(group, name);// 将当前线程添加到一个指定的线程组内
        this.queue = queue;
        this.name = name;
    }

    @Override
    // 添加了保护机制后的Clerk线程run()方法
    public void run() {
        Random rand = new Random();
        Transaction tran = null;
        String working = "woring";
        while (!working.equals("closed") || (!queue.isEmpty())) {
            try {
                tran = queue.get();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            System.out.println(this.name + "得到业务:" + tran);
            int newBalance = 0;// 记录业务完成后的新余额
            synchronized (tran.getAccount()) {
                if (tran.getTranType().compareTo(Transaction.DEPOSIT) == 0) {
                    newBalance = tran.getAccount().getBalance() + tran.getAmount();
                } else if (tran.getTranType().equals(Transaction.WITHDRAW)) {
                    newBalance = tran.getAccount().getBalance() - tran.getAmount();
                }
                try {
                    Thread.sleep(rand.nextInt(200 + rand.nextInt(3)));
                } catch (InterruptedException e) {
                    if (queue.isEmpty()) {
                        working = "closed";
                    }
                }
                tran.getAccount().setBalance(newBalance);// 休眠后，更新账户余额
                System.out.printf(this.name + "完成%d号业务处理，处理后账户余额是%d\r\n", tran.getNum(), newBalance);
            }// 结束保护
        }
    }

}
